// InfoBus.cpp : Defines the entry point for the DLL application.
//

#include "stdafx.h"
#include "InfoBus.h"
#include "XMLHelper.h"
#include "ComponentRegister.h"
#include "MetaXmlHandler.h"

#include <windows.h>
#include <sstream>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
	int nRetCode = 0;
	if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0)) {
    ::MessageBox(NULL, _T("Fatal Error: MFC initialization failed\n"), _T("Error"), MB_ICONERROR | MB_OK);
		nRetCode = 1;
	} 
	return nRetCode;
}

IListener::IListener(E_SUBJECT subj) 
: db(NULL)
{ 
  db = DatabaseAdapter::getInstance(subj);
  db->setListener(this);
  if (db) db->start();
}

IListener::~IListener() 
{ 
  if (db) delete db;
}

void IListener::setAliveBeats(bool bEnable)
{
  db->setAliveBeats(bEnable);
  if (bEnable) {
    ComponentRegister::getInstance()->registerComponent(db->getSender(), this->getType(), db->getSubjectText());
  } else { 
    ComponentRegister::getInstance()->unregisterComponent(db->getSender());
  }
}

const char* IListener::getSubjectText()
{
  return db->getSubjectText();
}

const char* IListener::getSender()
{
  return db->getSender();
}

Dispatcher::Dispatcher(E_SUBJECT subj) 
: db(NULL)
{ 
  db = DatabaseAdapter::getInstance(subj);
}

Dispatcher::~Dispatcher()
{
  if (db) delete db;
}

void Dispatcher::sendMessage(const char * m)
{
  if (m) {
    MetaXmlHandler xmlhnd(m);
    _bstr_t x = _bstr_t(xmlhnd.testXmlEx(_bstr_t("/*")));

    if (x != _bstr_t("")) {
      char * m2 = new char[x.length()+1];
      memset(m2, 0, x.length()+1);
      strncpy(m2, x, x.length());

      if (db) db->dispatch(m2);
      delete[] m2;
    } else {
      std::stringstream ss;
      ss << "Invalid message, nothing dispatched!" 
         << std::endl
         << "Message[" 
         << std::endl
         << m
         << std::endl
         << "]"
         << std::endl;
      // OutputDebugString("* Invalid message, nothing dispatched\n");
      ::MessageBox(NULL, ss.str().c_str(), "Warning", MB_ICONWARNING | MB_OK);
    }
  }
}

void Dispatcher::setAliveBeats(bool bEnable)
{
  db->setAliveBeats(bEnable);
  if (bEnable) {
    ComponentRegister::getInstance()->registerComponent(db->getSender(), this->getType(), db->getSubjectText());
  } else { 
    ComponentRegister::getInstance()->unregisterComponent(db->getSender());
  }
}


